// pages/index/analyse/analyse.js
let interstitialAd = null;
const downloadBaseUrl = "http://localhost:8700/media/download/transfer"
const downloadImageBaseUrl = "http://localhost:8700/media/download/transfer/image"
// const downloadImageBaseUrl = "http://localhost:8700/media/download/transfer/image"
Page({

    /**
     * 页面的初始数据
     */
    data: {
        videos:[],
        images:[],
        baseUrl:'',
        videosDownloadProgress:[],
        showVideoProgress:[],
        imagesDownloadProgress:[],
        showImageProgress:[],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        var app = getApp();
        this.setData({baseUrl: app.globalData.baseUrl})
        if(wx.createInterstitialAd){
          interstitialAd = wx.createInterstitialAd({ adUnitId: 'adunit-c04c8689d165224f' })
          interstitialAd.onLoad(() => {
            console.log('onLoad event emit')
          })
          interstitialAd.onError((err) => {
            console.log('onError event emit', err)
          })
          interstitialAd.onClose((res) => {
            console.log('onClose event emit', res)
          })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        var app = getApp();
        this.setData({
            videos: app.globalData.videos,
            images: app.globalData.images,
        })
        // 超过70秒可以显示插屏广告
        var currentTime = new Date();
        var lastTime = wx.getStorageSync('cpShowTime')
        var interval = (currentTime.getTime() -lastTime.getTime()) /1000;
        console.log("==间隔： "+interval)
        if (interval>70){
          wx.setStorageSync('cpShowTime', currentTime)
          interstitialAd.show().catch((err) => {
            console.error(err)
            wx.setStorageSync('cpShowTime', lastTime)
          })
        }

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    copyVideoAddress(e){
        console.log(e)
        wx.setClipboardData({
            data: e.currentTarget.dataset.url,
          })
    },
    downloadVideo(e){
        var flag = 1;
        var ts = this;
        var index = e.currentTarget.dataset.index;
        this.setData({['showVideoProgress['+index+']']:1});
        wx.downloadFile({
          url: e.currentTarget.dataset.url,

          success(res){
              wx.saveVideoToPhotosAlbum({
                filePath: res.tempFilePath,
                success(res){
                    wx.showModal({
                      title: '资源下载成功',
                      content: '下载成功，请前往相册查看',
                      complete: (res) => {
                        if (res.cancel) {
                        }
                        if (res.confirm) {
                        }
                      }
                    })
                }
              })
          },
          fail(res){
            wx.showLoading({
              title: '调用中转站下载',
            })
              flag = 2;
              let token = wx.getStorageSync("token");
              wx.downloadFile({
                url: downloadBaseUrl,
                header: {
                  Authorization: `Bearer ${token}`,
                  downloadUrl: e.currentTarget.dataset.url,
                },
                success(res){
                  wx.hideLoading()
                    wx.saveVideoToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success(res){
                            wx.showModal({
                              title: '资源下载成功',
                              content: '下载成功，请前往相册查看',
                              complete: (res) => {
                                if (res.cancel) {
                                }
                                if (res.confirm) {
                                }
                              }
                            })
                        }
                      })
                },
                fail(res){
                  wx.hideLoading()
                    wx.showModal({
                      title: '下载失败',
                      content: '服务器压力过大，请多试几次或者复制链接至浏览器下载哦',
                      complete: (res) => {
                        if (res.cancel) {  
                        }              
                        if (res.confirm) {                        
                        }
                      }
                    })
                    wx.request({
                        url: ts.data.baseUrl+"/media/analyse/add/exp",
                        method: "POST",
                        data: {openId: "XXXXXXXXXXXXXXXX",
                          username: e.currentTarget.dataset.url},
                      })
                }
              }).onProgressUpdate((res1)=>{
                if (flag === 2){
                    ts.setData({['videosDownloadProgress['+index+']']: res1.progress})
                  }
            })

          },
        }).onProgressUpdate((res)=>{
            if (flag === 1){
                ts.setData({['videosDownloadProgress['+index+']']: res.progress})
              }
        })
    },
    downloadVideos: function(){
        var videos = this.data.videos;
        for (let index = 0; index < videos.length; index++) {
            const vurl = videos[index];
            this.setData({['showVideoProgress['+index+']']:1});
            console.log(vurl)
            var ts = this;
            wx.downloadFile({
                url: vurl,
                success(res){
                    wx.saveVideoToPhotosAlbum({
                      filePath: res.tempFilePath,
                      success(res){
                        if(index==videos.length-1){
                            wx.showModal({
                                title: '资源下载成功',
                                content: '下载成功，请前往相册查看',
                                complete: (res) => {
                                  if (res.cancel) {
                                  }
                                  if (res.confirm) {
                                  }
                                }
                              })
                        }
                      }
                    })
                },
                fail(res){
                    wx.showModal({
                      title: '下载失败',
                      content: '服务器压力过大，请多试几次或者复制链接至浏览器下载哦',
                      complete: (res) => {
                        if (res.cancel) {
                        }
                    
                        if (res.confirm) {
                        }
                      }
                    })
                }
              }).onProgressUpdate((res)=>{
                ts.setData({['videosDownloadProgress['+index+']']: res.progress})
                //   ts.setData({videosDownloadProgress:(((index+1)/videos.length)+(res.progress/videos.length)),})
              })
        }
    },
    copyImageAddr(e){
        wx.setClipboardData({
            data: e.currentTarget.dataset.url,
          })
     },

    downloadImage(e){
       this.downloadIMG(e.currentTarget.dataset.url, true, e.currentTarget.dataset.index)
    },
    downloadIMG(imageUrl, flag, index){
        var ts = this;
        this.setData({['showImageProgress['+index+']']:1});
        wx.downloadFile({
          url: imageUrl,
          success(res){
            wx.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success(res){
                  if (flag){
                      wx.showModal({
                        title: '下载成功',
                        content: '图片下载成功，请前往相册查看',
                        complete: (res) => {
                          if (res.cancel) {
                            
                          }
                      
                          if (res.confirm) {
                            
                          }
                        }
                      })
                  }
              }
            })
        },
        fail(res){
          wx.showLoading({
            title: '正在调用中转站下载',
          })
          let token = wx.getStorageSync("token");
          wx.downloadFile({
            url: downloadImageBaseUrl,
            header: {
              Authorization: `Bearer ${token}`,
              downloadUrl: imageUrl,
            },
            success(res){
              wx.hideLoading()
              wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success(res){
                    if (flag){
                        wx.showModal({
                          title: '下载成功',
                          content: '图片下载成功，请前往相册查看',
                          complete: (res) => {
                            if (res.cancel) {
                              
                            }
                        
                            if (res.confirm) {
                              
                            }
                          }
                        })
                    }
                }
              })
            },
            fail(res){
              wx.hideLoading()
              wx.showModal({
                title: '资源下载失败',
                content: '服务器压力过大，请多试几次或者复制链接至浏览器下载哦~',
                complete: (res) => {
                  if (res.cancel) {           
                  }    
                  if (res.confirm) {      
                  }
                }
              })
            }
          }).onProgressUpdate((res2)=>{
            ts.setData({['imagesDownloadProgress['+index+']']:res2.progress})
        })
        }
        }).onProgressUpdate((res)=>{
            this.setData({['imagesDownloadProgress['+index+']']:res.progress})
        })
    },
    downloadImages:function(){
        var images = this.data.images;
        for (let index = 0; index < images.length; index++) {
            const element = images[index];
            if (index == images.length-1){
                this.downloadIMG(element, true, index);
            }else{
                this.downloadIMG(element, false, index);
            }
        }
    },
    adLoadB() {
      console.log('解析页面底部小程序视频广告加载成功')
    },
    adErrorB(err) {
      console.log('解析页面底部小程序视频广告加载失败', err)
    },
    adCloseB() {
      console.log('解析页面底部小程序视频广告关闭')
    },
})